// ExcessRecordManager.cpp: implementation of the ExcessRecordManager class.
//
//////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include "kwservercore.h"
#include "ExcessRecordManager.h"
#include "ExcessRecordThread.h"
#include "ServerConfiguration.h"

#include "CommonLib\Guard.h"

#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif

//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

ExcessRecordManager::ExcessRecordManager():
	m_pExcessRecordThread(NULL)
{
}

ExcessRecordManager::~ExcessRecordManager()
{
}

ExcessRecordManager * ExcessRecordManager::m_pInstance = NULL;

ExcessRecordManager * ExcessRecordManager::Instance()
{
	if (m_pInstance == NULL)
	{
		m_pInstance = new ExcessRecordManager;
	}

	return m_pInstance;
}

void ExcessRecordManager::DeleteInstance()
{
	if (m_pInstance) delete m_pInstance;

	m_pInstance = NULL;
}

void ExcessRecordManager::Init()
{
	CreateExcessRecordThread();
}

void ExcessRecordManager::Cleanup()
{
	DestroyExcessRecordThread();
}

ExcessRecordThread * ExcessRecordManager::CreateExcessRecordThread()
{
	if (!m_pExcessRecordThread)
	{
		m_pExcessRecordThread = new ExcessRecordThread();
		m_pExcessRecordThread->CreateThread(CREATE_SUSPENDED);
		m_eventDBInit.ResetEvent();
		m_pExcessRecordThread->ResumeThread();
		CSingleLock singlelock(&m_eventDBInit, TRUE);
	}

	return m_pExcessRecordThread;
}

void ExcessRecordManager::DestroyExcessRecordThread()
{
	if (m_pExcessRecordThread)
	{
		m_pExcessRecordThread->Cancel();
		m_pExcessRecordThread->Wait();
		delete m_pExcessRecordThread;
		m_pExcessRecordThread = NULL;
	}
}

void ExcessRecordManager::AppendExcessRecord(const ExcessRecord& er)
{
	Guard guard(&m_mutexRecords);

	ExcessRecord * pExcessRecord = new ExcessRecord(er);
	AddRecord(pExcessRecord);
}

bool ExcessRecordManager::TakeExcessRecord(ExcessRecord& er)
{
	Guard guard(&m_mutexRecords);

	ExcessRecord * pExcessRecord = (ExcessRecord *)GetFirstRecord();
	if (pExcessRecord)
	{
		er = *pExcessRecord;
		DeleteRecord(pExcessRecord);
		delete pExcessRecord;
		return true;
	}

	return false;
}